package com.colorfruit.admin.control.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.colorfruit.admin.control.annotation.Auth;
import com.colorfruit.framework.intercepter.BaseInterceptor;
import com.colorfruit.framework.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AuthInterceptor extends BaseInterceptor {

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            Auth authPassport = ((HandlerMethod) handler).getMethodAnnotation(Auth.class);

            //没有声明需要权限,或者声明不验证权限
            if(authPassport == null){
                return true;
            }else{
                //在这里实现自己的权限验证逻辑
                String userId = request.getHeader("userId");
                String token = request.getHeader("token");

                boolean authed = true;

                log.info("[admin-admin鉴权]userId:{},token:{}",userId,token);

                if (userId == null || token == null) {
                    authed = false;
                } else {
                    String serverToken = redisCache.getCache("TOKEN_" + userId, String.class);
                    log.info("[admin-admin鉴权]redis-token：{}",serverToken);
                    if(!token.equals(serverToken))
                        authed = false;
                }

                if (authed) {
                    return true;
                } else {
                    response.setStatus(403);
                    Map result = new HashMap();
                    result.put("code", 403);
                    result.put("message", "Invalid Auth Information");
                    result.put("data", new HashMap());
                    response.getWriter().write(new JSONObject(result).toJSONString());
                    return false;
                }
            }
        }else{
            return true;
        }
    }

}